package com.tarena.lbs.basic.web.controller;

import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.model.Result;
import com.tarena.lbs.base.protocol.pager.BasePageList;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.basic.web.service.AdminService;
import com.tarena.lbs.common.basic.converter.AdminConverter;
import com.tarena.lbs.pojo.basic.bo.AdminBO;
import com.tarena.lbs.pojo.basic.param.AdminParam;
import com.tarena.lbs.pojo.basic.query.AdminQuery;
import com.tarena.lbs.pojo.basic.vo.AdminVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/admin/basic/")
public class AdminController {
    @Autowired
    private AdminService adminService;

    //1 查询后台登录用户详情
    //2 adminVO accountType=0 平台管理员 1 商家用户 展示不同权限的页面菜单
    @GetMapping("role/detail")
    public Result<AdminVO> adminDetail() throws BusinessException {
        //1. 调用业务层 获取adminBO
        AdminBO adminBO = adminService.adminDetail();
        //2. 转化vo 封装result返回
        AdminVO vo=null;
        if (adminBO!=null){
            vo=new AdminVO();
            BeanUtils.copyProperties(adminBO,vo);
        }
        log.debug("C1-返回数据:{}",vo);
        return new Result<>(vo);
    }
    //平台管理查询账号 列表
//    @Autowired
//    private AdminConverter adminConverter;//在common中已有的转化器 暂时还没有bean
    @PostMapping("role/list")
    public Result<PageResult<AdminVO>> adminList(@RequestBody AdminQuery query) throws  BusinessException{
        //封装一个分页 需要4个属性pageNo pageSize<-query
        //total总数 objects 分页数据 需要业务查询 BasePageList
        log.debug("C2-前端查询参数:{}",query);
        query.setPageNo(1);
        query.setPageSize(10);
        BasePageList<AdminBO> adminBOS=adminService.adminList(query);
        //使用转化器 将adminBOS和query装配成一个新的分页对象
        if (adminBOS == null || adminBOS.getTotal() == 0) {
            return null;
        }
        PageResult<AdminVO> result = new PageResult<>();
        List<AdminVO> vos = new ArrayList<>();
        for (AdminBO temp : adminBOS.getList()) {
            AdminVO vo = new AdminVO();
            BeanUtils.copyProperties(temp,vo);
            vos.add(vo);
        }
        result.setTotal(adminBOS.getTotal());
        result.setObjects(vos);
        result.setPageNo(query.getPageNo());
        result.setPageSize(query.getPageSize());
        return new Result<>(result);
    }
    @PostMapping("role/add")
    public Result<Void> adminSave(@RequestBody AdminParam param) throws BusinessException{
        AdminBO adminBO=new AdminBO();
        BeanUtils.copyProperties(param,adminBO);
        adminBO.setCreateTime(new Date());
        adminService.adminSave(adminBO);
        return Result.success();
    }
}
